package com.yuuzy.qqserver.service;

import com.yuuzy.qqcommon.Message;
import com.yuuzy.qqcommon.MessageType;
import com.yuuzy.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 这是服务器，在监听9999，等待客户端的连接，并保持通信
 */
public class QQServer {
	private ServerSocket ss = null;
	//创建一个集合，存放多个用户，如果是这些用户登录，就认为是合法的
	//这里我们也可以使用
	//ConcurrentHashMap，可以处理并发的集合，线程安全
	private static ConcurrentHashMap<String,User> validUsers = new ConcurrentHashMap<>();
	static ConcurrentHashMap<String, ArrayList<Message>> messagehm = new ConcurrentHashMap<>();//key:userID,value:message

	static {
		//在静态代码块，初始化 validUsers
		validUsers.put("100",new User("100","123456"));
		validUsers.put("200",new User("200","123456"));
		validUsers.put("300",new User("300","123456"));
		validUsers.put("至尊宝",new User("至尊宝","123456"));
		validUsers.put("紫霞仙子",new User("紫霞仙子","123456"));
		validUsers.put("菩提老祖",new User("菩提老祖","123456"));
	}

	//验证用户登录
	private boolean checkUser(String userID, String pwd){
		User user = validUsers.get(userID);
		if (user == null) {
			//不存在
			return false;
		}
		//密码不对
		return user.getPassword().equals(pwd);
	}
	public QQServer() throws IOException, ClassNotFoundException {
		try {
			//注意：端口可以写在配置文件。
			System.out.println("服务端在9999端口监听...");
			ss = new ServerSocket(9999);
			//启动推送新闻的线程
			new Thread(new SendNewsToAllService()).start();
			while (true) {
				Socket socket = ss.accept();
				//得到socket关联的对象输入流
				ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
				User user = (User) objectInputStream.readObject();//读取客户端发送的User对象
				//得到socket关联的对象输出流
				ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
				//创建一个message对象，准备回复
				Message message = new Message();
				//验证
				if (checkUser(user.getUserID(), user.getPassword())) {//合法
					message.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);
					//将message对象回复
					objectOutputStream.writeObject(message);
					//创建一个线程，和客户端保持通信，该线程需要持有socket对象
					ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket, user.getUserID());
					serverConnectClientThread.start();
					//把该线程对象放入一个集合中进行管理
					ManageClientThreads.addClientThread(user.getUserID(), serverConnectClientThread);
				} else {
					//登录失败
					message.setMesType(MessageType.MESSAGE_LOGIN_FAIL);
					objectOutputStream.writeObject(message);
					socket.close();
				}
			}
		} finally {
			//退出while循环，关闭资源
			if (ss != null) {
				ss.close();
			}
		}

	}
}
